from rest_framework import serializers
from api.models import Product, ProductFormula

class ProductFormulaSerializer(serializers.ModelSerializer):
    id = serializers.IntegerField(required=False)
    
    class Meta:
        model = ProductFormula
        fields = ['id', 'material_id', 'material_name', 'quantity_required']


class ProductListSerializer(serializers.ModelSerializer):
    class Meta:
        model = Product
        fields = "__all__"


class ProductSerializer(serializers.ModelSerializer):
    formula = ProductFormulaSerializer(required=True, many=True)

    class Meta:
        model = Product
        fields = ['product_id', 'product_name', 'version', 'description', 'creation_date', 'status', 'formula']

    def create(self, validated_data):
        formulas_data = validated_data.pop('formula')
        product = Product.objects.create(**validated_data)

        for formula in formulas_data:
            ProductFormula.objects.create(product=product, **formula)
        
        return product

    def update(self, instance, validated_data):
        formulas = validated_data.pop('formula')
    
        # 更新主模型字段
        for attr, value in validated_data.items():
            setattr(instance, attr, value)
        instance.save()

        # 获取现有关联对象
        existing_formulas = {f.id: f for f in instance.formula.all()}
        
        # 处理每个传入的关联对象
        for formula_data in formulas:
            formula_id = formula_data.get('id')
            if formula_id and formula_id in existing_formulas:
                # 更新现有对象
                formula = existing_formulas[formula_id]
                for key, value in formula_data.items():
                    setattr(formula, key, value)
                formula.save()
                existing_formulas.pop(formula_id)  # 标记为已处理
            else:
                # 创建新对象
                ProductFormula.objects.create(product=instance, **formula_data)
        
        # 删除未处理的关联对象（前端未传入的）
        for formula in existing_formulas.values():
            formula.delete()

        return instance